package br.pro.raphael.airlinerecovery.servlet;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.pro.raphael.air.Airport;
import br.pro.raphael.air.Flight;
import br.pro.raphael.air.Airline;
import br.pro.raphael.util.PMF;

@SuppressWarnings("serial")
public class CargaVoos extends HttpServlet{	
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		
		DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
		String arquivo = req.getParameter("arquivo");
        URL url = new URL("http://raphael.dominiotemporario.com/antrouting/" + arquivo);
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        String line;
        
        List<Flight> voos = new LinkedList();
        
        
    	

        /*Query query = pm.newQuery(Airline.class,"nome == 'TRIP'");
        List<Airline> empresas = (List<Airline>) query.execute();
        Airline empresa = (Airline)empresas.get(0);*/

        while ((line = reader.readLine()) != null) {
        	
        	
        	Flight voo = new Flight();
        	String s[] = line.split(";");
        	//voo.setEmpresa(empresa);
        	voo.setVoo(s[1]);
        	voo.setAeronave(s[2]);
        	voo.setEquipamento(s[3]);
        	voo.setAssentos(Integer.parseInt(s[4]));
        	voo.setEtapa(Integer.parseInt(s[6]));
        	voo.setOrigem(s[7]);
        	voo.setDestino(s[8]);
        	voo.setEmpresa("TRIP");
        	try {
				voo.setPartida(sdf.parse(s[9]));
				voo.setChegada(sdf.parse(s[10]));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	
			
			voos.add(voo);
        	resp.getWriter().println(line);
        }
        
        PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.makePersistentAll(voos);
		pm.close();
    	
      
        
        reader.close();

	


		resp.getWriter().println("xxxx");
		
	}

}
